package com.kabao.demo;


import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class RequestWrapper extends HttpServletRequestWrapper {
    /**
     * 用于缓存请求体数据的字节数组
     */
    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 读取请求体数据并转换为字节数组进行存储，防止InputStream被消费后无法重复读取
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }

    // 获取请求体的字符串内容
    public String getBodyString() {
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        // 返回包装后的 BufferedReader，使请求体可多次读取
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 用已缓存的字节数组创建新的输入流，确保请求体可重复读取
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read(); // 读取字节数据
            }

            @Override
            public boolean isFinished() {
                return bais.available() == 0; // 判断是否读取完毕
            }

            @Override
            public boolean isReady() {
                return true; // 随时可以读取
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // 这里不做特殊处理
            }
        };
    }
}